/*
 * Copyright (C) 2020 The LINN Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.juqimiao.linn.boot;

import com.juqimiao.linn.context.ApplicationContextWrapperI;
import com.juqimiao.linn.registry.RegistryI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.Order;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 框架启动程序。
 * 它将自动调用在所有实现{@link RegistryI}并通过{@link org.springframework.stereotype.Component}
 * 标注的注册器，进行组件注册和初始化。
 *
 * 可以通过 {@link Order}进行标注，注册机制将根据Order.value值确定注册次序。
 * value的数值越小将越先册和初始化。
 *
 * @author Collin Cai
 */
@ComponentScan(basePackages = Bootstrapper.BASE_PACKAGES)
public class Bootstrapper {

    public static final String BASE_PACKAGES = "com.juqimiao.linn";

    private static AtomicBoolean isLoaded = new AtomicBoolean(false);
    @Autowired
    private ApplicationContextWrapperI applicationContextWrapper;

    public Bootstrapper() {

    }

    /**
     * 初始化组件注册配置。
     */
    public void initialize() {
        if(isLoaded.compareAndSet(false, true)) {
            Map<String, RegistryI> map = applicationContextWrapper.getBeansOfType(RegistryI.class);
            List<RegistryOrder> list = new ArrayList<>();
            map.forEach((key, register) -> {
                Order order = register.getClass().getAnnotation(Order.class);
                int orderValue = 0;
                if (order != null) {
                    orderValue = order.value();
                }
                RegistryOrder registryOrder = new RegistryOrder(register, orderValue);
                list.add(registryOrder);
            });
            Collections.sort(list);
            list.forEach(registryOrder -> {
                registryOrder.registry.register();
            });
            System.out.println(isLoaded.get());
        }
    }

    private class RegistryOrder implements Comparable<RegistryOrder> {
        private int order;
        private RegistryI registry;

        RegistryOrder(RegistryI registry, int order) {
            this.registry = registry;
            this.order = order;
        }

        @Override
        public int compareTo(RegistryOrder o) {
            if (o == null) {
                return 0;
            }

            return this.order - o.order;
        }
    }
}
